﻿using System.ComponentModel;

namespace Aliphant.Common.Helper
{
    public static class EnumExtension
    {
        /// <summary>
        /// 通过Description获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        public static T GetEnumByDescription<T>(string description) where T : Enum
        {
            foreach (var e in Enum.GetValues(typeof(T)))
            {
                if (e == null) continue;
                bool? res = e.GetType().GetField(e.ToString() ?? string.Empty)?
                    .GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .Select(a => (a is DescriptionAttribute dp) && dp.Description == description)
                    .FirstOrDefault();
                if (res.HasValue && res.Value)
                    return (T)e;

                //object[] attrs = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                //if (attrs == null || attrs.Length <= 0)
                //{
                //    throw new NullReferenceException();
                //}
                //var desc = (DescriptionAttribute)attrs[0];
                //if (desc.Description == description) return (T)e;
            }

            throw new InvalidEnumArgumentException();
        }

        /// <summary>
        /// 获取枚举Description
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum em)
        {
            return em?.GetType()?.GetField(em.ToString())?
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .Select(a => a as DescriptionAttribute)
                .FirstOrDefault()?.Description ??
                (em?.ToString() ?? string.Empty);
        }
    }
}
